package com.tanhua.sso.controller;

import com.tanhua.common.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){

        try {
            //手机号
            String phone = param.get("phone");
            //验证码
            String code = param.get("verificationCode");

            //校验手机号和验证码是否匹配
            Map<String,Object> data = userService.login(phone, code);

            //data不是null 就是登陆成功
            if (data != null) {
                //创建一个集合保存要返回给前端的信息
//                Map<String, Object> result = new HashMap<>(2);
                //将service处理好的数据分成token和isNew
//                String[] ss = StringUtils.split(data, "|");
                //存入result集合中
//                result.put("token", ss[0]);
//                result.put("isNew", Boolean.valueOf(ss[1]));

                //返回给前端
                return ResponseEntity.ok(data);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //出现异常，登录失败后，返回给前端的对象
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败！").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 对外提供的校验token接口
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token){

        return userService.queryUserByToken(token);
    }
}
